package com.zjz.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class ImageServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //如何让浏览器5s自动刷新一次
        resp.setHeader("refresh","3");

        //在内存中创建一个图片
        BufferedImage bufferedImage = new BufferedImage(80, 20, BufferedImage.TYPE_3BYTE_BGR);
        //得到图片
        Graphics2D graphics = bufferedImage.createGraphics();
        //设置图片的背景颜色
        graphics.setColor(Color.white);

        graphics.fillRect(0,0,80,20);

        //给图写数据
        graphics.setColor(Color.ORANGE);
        graphics.setFont(new Font(null,Font.BOLD,20));

        graphics.drawString(MakeNum(),0,20);

        //告诉浏览器，这个请求用图片形式打开
        resp.setContentType("image/jpeg");

        ImageIO.write(bufferedImage,"jpg",resp.getOutputStream());


    }


    //生成随机数
    public String MakeNum(){
        Random random = new Random();
        String s = random.nextInt(99999999) + "";  //此时生成的不一定是7位
        StringBuffer stringBuffer = new StringBuffer();
        for(int i = 0;i < 7-s.length();i++){
            stringBuffer.append("0");
        }

        String s1 = stringBuffer.toString() + s;
        return s1;


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
